package com.gzhryc.servlet.upload;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 上传的文件集对象 <br/>
 * 1. 支持多文件上传
 * @author zhanghao
 * 
 */
public class UploadFiles {

	List<FileItem> fileItemList = null;
	List<FileItem> realFileItems = null;
	final ServletFileUpload servletFileUpload;
	
	public UploadFiles(HttpServletRequest request,ServletFileUpload servletFileUpload) {
		this.servletFileUpload = servletFileUpload;
		try {
			fileItemList = servletFileUpload.parseRequest(request);
			if(fileItemList != null && fileItemList.size() > 0){
				for(FileItem item : fileItemList) {
					if(item.isFormField()) {
						try {
							request.setAttribute(item.getFieldName(), item.getString("UTF-8"));
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
					}else {
						if(realFileItems == null) {
							realFileItems = new ArrayList<FileItem>();
						}
						realFileItems.add(item);
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}
	
	public List<FileItem> getFiles(){
		return realFileItems;
	}

	public FileItem getFirstFile() {
		if(realFileItems != null && realFileItems.size() > 0) {
			return realFileItems.get(0);
		}
		return null;
	}

	public List<FileItem> getFileItemList(){
		return fileItemList;
	}

	public ServletFileUpload getServletFileUpload() {
		return this.servletFileUpload;
	}
	
	public static UploadFiles tryBuild(HttpServletRequest request,ServletFileUpload fileUpload) {
		//检查请求类型
		if(request.getContentType() != null && request.getContentType()
				.toLowerCase(Locale.ENGLISH).startsWith("multipart/form-data")){
			return new UploadFiles(request,fileUpload);
		}
		return null;
	}

}
